<?php
/*
 * @param auther: feyeen Date: 2016/4/8 Time: 11:14
 * @param OrderDetailsController.php
 */
namespace liketry\controllers;

use services\models\Order;
use services\models\OrderInfo;
use yii;
use yii\widgets\LinkPager;
use services\models\OrderInfoDetail;
use services\models\PayLog;
use leyestd\alipay\AlipayCloseOrder;
use common\models\OrderInfoHistory;


class OrderDetailsController extends CustomController{

    //关闭视图
    //public $layout=false;
    //订单下单成功
    public function actionOrderResult(){
        try {
            //获取对应的订单ID
            $order_info_id = intval(Yii::$app->request->get('order_info_id'));
            if(empty($order_info_id)){
                return false;
            }

            $params['order_info.order_info_id'] = $order_info_id;
            $params['order_info.bestry_uid'] = $this->bestry_uid;

            //查询订单信息
            $OrderInfoDetail = new OrderInfoDetail();
            $orderInfo    = $OrderInfoDetail->getOrderInfos($params);


            if($orderInfo['lgistics']['telephone'])
                $orderInfo['lgistics']['telephone'] = substr_replace($orderInfo['lgistics']['telephone'],'****',3,4);
            return $this->render('@liketry/views/cart/payed', ['orderInfo' => $orderInfo]);
        }catch (yii\base\Exception $e){
            return $e->getMessage();
        }
    }
    //订单列表页
    public function actionOrderList(){
        //查询用户的订单
        if(self::verification() == false)
            return $this->redirect($this->login_url);

        $params['bestry_uid'] = $this->bestry_uid;

        $timesolt = Yii::$app->request->get('timesolt');

        //历史订单不处理
        if($timesolt == 1 || !isset($timesolt))
            $params['update_time'] = strtotime("-3 month");

        $status = Yii::$app->request->get('status');
            
        //满足状态是空或者是在订单设置状态内
        if(!array_key_exists($status,OrderInfo::$STATUS_DESC) && !empty($status)){
            return $this->redirect(['order-details/order-list']);
        }

        if(isset($status) && $status !=='')
            $params['status'] = $status;

        //分页问题
        $page = Yii::$app->request->get('page');
        $perpage = Yii::$app->request->get('per-page');
        $params['pages'] = !empty($page)? intval($page) : 1;                    //第几页
        $params['pagessize'] = !empty($perpage) ? intval($perpage) :10 ;        //每页   TODO 公用变量

        $timeStart = !empty($params['update_time'])?$params['update_time']:0;
        //获取订单信息
        $OrderInfoDetail = new OrderInfoDetail();

        $orderInfo    = $OrderInfoDetail->getUidOrderInfo($params,1);

        //代付款订单
        $orderPay      = $OrderInfoDetail->orderInfoNum($params,OrderInfo::$STATUS_ORDER_CREATED);

        //待收货
        $orderReceipt  =$OrderInfoDetail->orderInfoNum($params,OrderInfo::$STATUS_TO_SHIP);

        //待评价
        $orderEvaluate =$OrderInfoDetail->orderInfoNum($params,OrderInfo::$STATUS_ORDER_OK);

        //处理分页
        $page = LinkPager::widget(['pagination' => $orderInfo['page']]);

        return $this->render('order-list',['orderInfo'=>$orderInfo['data'],'page'=>$page,'orderPay'=>$orderPay,'orderReceipt'=>$orderReceipt,'orderEvaluate'=>$orderEvaluate]);
    }

    //返回订单的数量
    public function actionOrderStausNum(){
        $callback = Yii::$app->request->get('callback',null);
        $format = $callback ? \yii\web\Response::FORMAT_JSONP : \yii\web\Response::FORMAT_JSON;;
        Yii::$app->response->format = $format;

        $OrderInfoDetail = new OrderInfoDetail();
        //校验member_uid
        if(empty($this->bestry_uid))
            return ['data'=>'','msg'=>'参数错误！','flg'=>false];

        $param['bestry_uid']    =$this->bestry_uid;
        $param['update_time'] = strtotime("-3 month");
        //带付款订单 0
        $orderPay = $OrderInfoDetail->orderInfoNum($param,OrderInfo::$STATUS_ORDER_CREATED);
        $orderpayUrl =Yii::$app->request->hostInfo.Yii::$app->urlManager->createUrl(["order-details/order-list",'status'=>0]);

        //待确认订单 3
        $orderSure = $OrderInfoDetail->orderInfoNum($param,OrderInfo::$STATUS_TO_SHIP);
        $orderSureUrl =Yii::$app->request->hostInfo.Yii::$app->urlManager->createUrl(["order-details/order-list",'status'=>3]);

        //待评论 5
        $comment = $OrderInfoDetail->orderInfoNum($param,OrderInfo::$STATUS_ORDER_OK);
        $commentUrl =Yii::$app->request->hostInfo.Yii::$app->urlManager->createUrl(["order-details/order-list",'status'=>5]);

       $dataInfo = array(
           array('amount'=>$orderPay['num'],'url'=>$orderpayUrl),
           array('amount'=>$orderSure['num'],'url'=>$orderSureUrl),
           array('amount'=>$comment['num'],'url'=>$commentUrl),
       );
        $result = ['data'=>$dataInfo,'msg'=>'','flag'=>true];
        if($callback){
            return array(
                'callback' => $callback,
                'data' => $result
            );
        }

        return $result;
    }


    //修改订单状态
    public function actionOrderStatus(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;   //依照json返回
        $status = intval(Yii::$app->request->get('status'));
        $pay_status = intval(Yii::$app->request->get('pay_status'));
        $id = intval(Yii::$app->request->get('id'));

        if(empty($id))
            return array('data'=>'','msg'=>'订单id不能为空','code'=>'-401');

        $orderInfo = new OrderInfoDetail();
        $orderInfo->findOne($id);
        $orderInfo->status =$status ;
        $orderInfo->pay_status = $pay_status;

        if($orderInfo->validate($orderInfo->attributes['status'])){
            if($orderInfo->save())
                return array('data'=>$id,'msg'=>'订单状态修改成功！','code'=>'200');
            else
                return array('data'=>$id,'msg'=>'订单状态修改失败','code'=>'-402');
        }

        return array('data'=>$id,'msg'=>'订单参数验证失败！','code'=>'-403');

    }

    //返回个人中心 订单的数量

    public function actionOrderNum(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;   //依照json返回

        $params['bestry_uid'] = $this->bestry_id;

        $OrderInfoDetail = new OrderInfoDetail();
        $orderInfo    = $OrderInfoDetail->getUidOrderInfo($params,2);

        return array('data'=>$orderInfo['data'],'msg'=>'用户中心订单数量','code'=>200);
    }


    //订单详情页
    /**
     * @return string
     */
    public function actionOrderDetail(){
        //订单信息
        if(self::verification() == false)
           return $this->redirect($this->login_url);

        $order_info_id = intval(Yii::$app->request->get('order_info_id'));

        if(self::verification($order_info_id) == false)
            throw new yii\web\NotFoundHttpException(false);

        $params['order_info.order_info_id'] = $order_info_id;
        $params['order_info.bestry_uid']    = $this->bestry_uid;

        //先查询三个月之前的订单，如果没有怎表示历史订单
        $OrderInfoDetail = new OrderInfoDetail();
        $orderInfo = $OrderInfoDetail->getOrderInfo($params);


        if(empty($orderInfo))
            throw new yii\web\NotFoundHttpException(false);

        //获取对应的商品信息
        $orderGoods = $OrderInfoDetail->getOrderGoodsList($orderInfo['order_info_id'],$params['historyId']);

        if(isset($orderInfo->lgistics->delivery_code)){
            $deliver_code   = $orderInfo->lgistics->delivery_code;
            $logic          = $OrderInfoDetail->getLogic($deliver_code,$orderInfo->order_sn);
        }else{
            $logic          = '';
            $deliver_code   = '';
        }


        /* //获取试豆
         $meberInfoUid   = MemberInfoBestry::getMemberIdByBestryUid($this->bestry_uid);
         $memberScore    = MemberScore::getScoreFromMemberInfoNo($meberInfoUid);*/
        return $this->render('order-detail',['orderInfo'=>$orderInfo,'orderGoods'=>$orderGoods,'logic'=>$logic]);
    }

    //根据订单id查询配货信息
    public function actionExpress(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;   //依照json返回
        $orderInfoId = Yii::$app->request->get('orderInfoId');
        if(empty($orderInfoId))
            return ['data'=>'','error_code'=>-401,'msg'=>'没有订单信息，请查证'];
        //获取订单信息
        $OrderInfoDetail = new OrderInfoDetail();

        return $OrderInfoDetail->orderInfoExpress($orderInfoId);
    }

    //取消订单
    public function actionCancelOrder(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;   //依照json返回
        $order_info_id = Yii::$app->request->get('order_info_id');
        if(empty($order_info_id))
            return ['flag' => false, 'msg' => '订单参数错误', 'errCode' => ''];

        $orderInfo     = OrderInfo::find()->where(['bestry_uid'=>$this->bestry_uid,'order_info_id'=>$order_info_id])->one();

        //没有订单信息则查询历史订单
        if(empty($orderInfo))
            $orderInfo = OrderInfoHistory::find()->where(['bestry_uid'=>$this->bestry_uid,'order_info_id'=>$order_info_id])->one();

        //取消订单
        if(!$orderInfo){
            return ['flag' => false, 'msg' => '暂无订单信息', 'errCode' =>''];
        }

        $order = new Order();
        $order->order_info_id   =$order_info_id;
        $order->bestry_uid      = $this->bestry_uid;

        if (!$order->cancelOrder()) {
            return ['flag' => false, 'msg' => '取消订单失败', 'errCode' => $order->getErrors()];
        }else{

            //第一支付为支付宝时，删除支付记录  暂时不做验证支付宝有延迟
            if(OrderInfoDetail::$STATUS_ORDER_CREATED == $orderInfo->status && OrderInfoDetail::$PAY_STATUS_WAIT==$orderInfo->pay_status){
                $payInfo = PayLog::find()->select('order_sn')->where(['bestry_uid'=>$this->bestry_uid,'order_info_id'=>$orderInfo->order_info_id,'order_sn'=>$orderInfo->order_sn,'pay_id'=>'1'])->one();
                if($payInfo){
                    $AlipayCloseOrder= new AlipayCloseOrder();
                    $AlipayCloseOrder->closeOrder($payInfo->order_sn);
                }
            }

            return  ['flag' => true, 'msg' => '取消订单成功', 'errCode' => '200'];
        }


    }

    //确认收货
    public function actionSureOrder(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;   //依照json返回
        $order_info_id = Yii::$app->request->get('order_info_id');
        if(!$order_info_id)
            return ['flag' => false, 'msg' => '订单参数错误！', 'errCode' =>'-400'];
        $order_info     = OrderInfo::find()->select(['bestry_uid','status','pay_status','order_amount','order_info_id'])->where(['order_info_id'=>$order_info_id])->one();

        //没有订单信息则查询历史订单
        $historyId      = 0;
        if(empty($order_info)){
            $historyId  = 1;
            $order_info = OrderInfoHistory::find()->select(['bestry_uid','status','pay_status','order_amount','order_info_id'])->where(['order_info_id'=>$order_info_id])->one();
        }

        if(!$order_info)
            return ['flag' => false, 'msg' => '暂无收货订单！', 'errCode' =>'-400'];
        try{
            //确认3个月之前的订单
            if(0 == $historyId && Order::orderStatusChange($order_info->order_info_id,OrderInfoDetail::$STATUS_ORDER_OK,$order_info->pay_status))
                return  ['flag' => true, 'msg' => '确认收货成功！', 'errCode' => '200'];


            //确认历史订单
            if(1 == $historyId && Order::orderStatusChangeHistory($order_info->order_info_id,OrderInfoDetail::$STATUS_ORDER_OK,$order_info->pay_status))
                return  ['flag' => true, 'msg' => '确认收货成功！', 'errCode' => '200'];


            return ['flag' => false, 'msg' => '确认收货失败！', 'errCode' =>'-400'];

        }catch (yii\base\Exception $e){
            throw new yii\base\Exception($e->getMessage());
        }

    }

    private function verification($orderInfoId=''){
        //验证登录
        if(!$this->isLogin()){
            return false;
        }

        if(empty($this->bestry_uid) || $this->bestry_uid < 0){
            return false;
        }

        if(!empty($orderInfoId) && $orderInfoId < 0){
            return false;
        }

        return true;
    }

}
